package com.ep.thirdPlatformProject.mq.controller;

import com.ep.thirdPlatformProject.system.config.websocket.WebSocketServer;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.HtmlUtils;

import java.util.Arrays;

@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping(value = "/websocket", produces ="json/application")
public class WebSocketController {

    private final WebSocketServer webSocket;

    @GetMapping("/sendNotification")
    public void sendNotification(String userId) {
        try {
            // 创建业务消息信息
            String message = "postman调用接口访问后端服务器存储数据并使用websocket将消息推送给前端客户端";

            // 全体发送
            webSocket.sendAllMessage(message);



            String message1 = "【websocket消息】 单点消息:只发送给id为"+userId+"的用户。";
            webSocket.sendOneMessage(userId, message1);

            // 多个用户发送 (userIds为多个用户id，逗号‘,’分隔)
            String[] userIds = {"1", "2"};
            String message2 = "【websocket消息】 单点消息:只发送给id为"+ Arrays.toString(userIds) +"的用户。";

            webSocket.sendOneMessage(userId, message2);
        } catch (Exception e) {
            log.error("e:{}", e.getMessage(), e);
            throw new RuntimeException(e);
        }

    }





    @MessageMapping("/hello")
    @SendTo("/topic/greetings")
    public String greeting(String message){

        return "hello,"+ HtmlUtils.htmlEscape(message)+"!";
    }



}
